import os
import sys
import traceback

from runProgram import *

def dofile(fname):
    f = open(fname)
    results = f.readline()
    assert(results.startswith('//$'))
    results = results[3:]
    results = map(float, results.split())
    f.close()

    print 'Running test: %s' % fname
    
    grammar = "grammar.py"

    try:
        bytecode = compileTarget(fname, grammar)
        res = run(bytecode, True, False)
    except:
        traceback.print_exc(file=sys.stdout)
        print 'Failed %s' % fname
        sys.exit(0)

    if res != results:
        print 'ERROR %s' % fname
        print 'Expected:', results
        print 'Gotten  :', res
        assert(False)

fnames = []
prefix = './tests'
if len(sys.argv) > 1:
    fnames = sys.argv[1:]
else:
    fnames = map(lambda x: os.path.join(prefix, x), os.listdir(prefix))

for fname in fnames:
    if not fname.endswith('.test'):
        continue
    
    dofile(fname)
    
print
print 'No errors!'

    
